<?php

/**
 *   商品套装
 *   上海百胜软件有限公司
 *   网站地址: http://baison.com.cn;
 *   author:  fillbag  286116033
 */

define('IN_OS', true);

require_once(dirname(__FILE__) . '/includes/init.php');
require_once(dirname(__FILE__) . '/includes/lib_group_promotion.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

/*------------------------------------------------------ */
//-- act 操作项的初始化
/*------------------------------------------------------ */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}

/*------------------------------------------------------ */
//-- 拍卖活动列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list'){
    /* 取得拍卖活动总数 */
    $count = group_pro_count();
    if ($count > 0)
    {
        /* 取得每页记录数 */
        $size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;

        /* 计算总页数 */
        $page_count = ceil($count / $size);

        /* 取得当前页 */
        $page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1;
        $page = $page > $page_count ? $page_count : $page;

        /* 缓存id：语言 - 每页记录数 - 当前页 */
        $cache_id = $_CFG['lang'] . '-' . $size . '-' . $page;
        $cache_id = sprintf('%X', crc32($cache_id));
    }
    else
    {
        /* 缓存id：语言 */
        $cache_id = $_CFG['lang'];
        $cache_id = sprintf('%X', crc32($cache_id));
    }
    /* 如果没有缓存，生成缓存 */
    if (!$smarty->is_cached('group_promotion_list.dwt', $cache_id))
    {
        if ($count > 0)
        {
            /* 取得当前页的拍卖活动 */
            $group_pro_list = group_pro_list($size, $page);
            $smarty->assign('group_pro_list',  $group_pro_list);
            /* 设置分页链接 */
            $pager = get_pager('auction.php', array('act' => 'list'), $count, $page, $size);
            $smarty->assign('pager', $pager);
        }
   
        /* 模板赋值 */
        $smarty->assign('cfg', $_CFG);
        assign_template();
        $position = assign_ur_here();
        $smarty->assign('page_title', $position['title']);    // 页面标题
        $smarty->assign('ur_here',    $position['ur_here']);  // 当前位置
        $smarty->assign('categories', get_categories_tree()); // 分类树
        $smarty->assign('helps',      get_shop_help());       // 网店帮助
        $smarty->assign('top_goods',  get_top10());           // 销售排行
        $smarty->assign('promotion_info', get_promotion_info());

        assign_dynamic('goods');	
    }
	$smarty->display('group_promotion_list.dwt', $cache_id);	
}elseif ($_REQUEST['act'] == 'view'){
    /* 取得参数：商品套装id */
    $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    if ($id <= 0)
    {
        os_header("Location: ./\n");
        exit;
    }
    
    /* 取得商品套装信息 */
    $group_pro = group_pro_info($id);
    
    if (empty($group_pro)){
        os_header("Location: ./\n");
        exit;
    }
    
    /* 缓存id：语言，商品套装id，状态，如果是进行中 */
    $cache_id = $_CFG['lang'] . '-' . $id . '-' . $group_pro['status_no'];
    if ($group_pro['status_no'] == 1){
       $cache_id = $cache_id . '-' . $group_pro['add_time'];
    }elseif ($group_pro['status_no'] == 2 && $group_pro['order_count'] == 0){
        $cache_id = $cache_id . '-' . $group_pro['add_time'] . '-1';
    }

    $cache_id = sprintf('%X', crc32($cache_id));

    /* 如果没有缓存，生成缓存 */
    if (!$smarty->is_cached('group_promotion.dwt', $cache_id)) {
    	$group_pro['gmt_end_time'] = local_strtotime($group_pro['end_time']);

        $group_pro_gallery= $db->getRow("select img_original as group_pro_img from ".$os->table('group_promotion_gallery')." where  is_reveal=1 AND group_promotion_id = '$id' order by img_id desc limit 1");
        if($group_pro_gallery === false){
           $group_pro_gallery = array();
        }
        $group_pro_goods_type = group_pro_goods_type($id);
        if($group_pro_goods_type['group_pro_r_count']>0){
        	$group_pro['group_pro_r_count'] = $group_pro_goods_type['group_pro_r_count'];
        }
        $pictures = get_group_pro_gallery($id);
        $smarty->assign('group_pro',array_merge($group_pro,$group_pro_gallery));
        $smarty->assign('pictures',            $pictures);  
        $smarty->assign('helps',      get_shop_help());       // 网店帮助
        $smarty->assign('group_pro_goods_type_list',            $group_pro_goods_type['list']);  
        assign_dynamic('goods');
    }

 	assign_template();
    $smarty->assign('switch_color_img',$_CFG['switch_color_img']);
    $smarty->assign('goods_id',$goods['goods_id']);  	   
    $smarty->assign('now_time',  gmtime());           // 当前系统时间
	$smarty->display('group_promotion.dwt');
		
}elseif($_REQUEST['act'] == 'goods_detail'){	
	
    include('includes/cls_json.php');
    $json = new JSON;
    $filters = $json->decode($_GET['JSON']);
    $res    = array('message' => '', 'html' => '');   
	$sql= "SELECT gpg.goods_type_id,gpg.goods_id,t.goods_count,t.is_present,t.add_money,gp.price_type,gp.price,gp.discount FROM " . 
	      $os->table('group_promotion_goods') . " gpg LEFT JOIN (" . $os->table('group_promotion_goods_type') . 
	      " t CROSS JOIN " . $os->table('group_promotion') . " gp) ON (gpg.goods_type_id=t.goods_type_id AND ".
	      " gpg.group_promotion_id=gp.group_promotion_id) WHERE gpg.goods_type_id = " . intval($filters->type) . " AND gpg.goods_id = " . 
	      intval($filters->value) . " LIMIT 1";    
    $gpg_row = $db->getRow($sql);
     /* 获得商品的信息 */
    $goods = get_goods_info($gpg_row['goods_id']);   
    if ($goods === false){
        /* 如果没有找到任何记录则跳回到首页 */
        $res['message'] = 'error';
    }else{
        if ($goods['brand_id'] > 0){
            $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']);
        }
        $size_lib = array();
        if($goods['size_lib_id']>0){
        	$size_lib = $db->getRow("SELECT lib_id,is_define,site_url FROM ".$os->table('size_lib')." WHERE lib_id=".intval($goods['size_lib_id']));
        	unset($goods['size_lib_id']);
        	if($size_lib && $size_lib['lib_id']>0){
            	$goods = array_merge($goods,$size_lib);
        	}
        }
        if($gpg_row['price_type']==1){
        	$goods['goods_price'] = floatval($gpg_row['add_money'] / $gpg_row['goods_count']);
        }elseif($gpg_row['price_type']==2){
        	if($gpg_row['is_present']==1){
        		$goods['goods_price'] = floatval($gpg_row['add_money'] / $gpg_row['goods_count']);
        	}else{
        		$goods['goods_price'] = floatval($goods['shop_price'] * ($gpg_row['discount']/100));
        	}
        }
	    $smarty->assign('goods',$goods);
	    unset($goods);
	    $smarty->assign('pictures', get_goods_gallery($gpg_row['goods_id'],0));  // 商品相册
		$properties = get_goods_specs($gpg_row['goods_id']);
		
        // 修改by贾军
        $specs_color = sizeof($properties['color'][0]);
        $specs_size  = sizeof($properties['size'][0]);        
        $color_flag = $specs_color > 1 ?'':'-1';
        $size_flag  = $specs_size  > 1 ?'':'-1';
        $smarty->assign('color_flag',$color_flag);              
        $smarty->assign('size_flag',$size_flag);		
		
		$smarty->assign('properties',$properties);//颜色尺码
        $smarty->assign('switch_color_img',$_CFG['switch_color_img']);
        $smarty->assign('goods_id',$goods['goods_id']);		
		$goods_inventory_link = 'goods.php?act=view_inv&id=';	
        unset($properties);
		$smarty->assign('goods_type_id',$gpg_row['goods_type_id']);
		unset($gpg_row);
    }
    
	$smarty->assign('goods_inventory_link',$goods_inventory_link);     

    $res['html']  = $smarty->fetch('group_pro_goods.dwt');
    die($json->encode($res));	
    
}elseif($_REQUEST['act']=='add_to_tmp_cart'){	
    include('includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);	
    $res    = array('error' => '', 'html' => '' , 'data'=>'');   
    if($_SESSION['user_id'] <= 0){
    	$res['error'] = '您尚未登录！';
    }
       
    $tmp_c_row = array();
	$sql= "SELECT gpg.goods_type_id,gpg.goods_id,t.goods_type_name,t.goods_count,t.is_present,t.add_money,gp.price_type,gp.price,gp.discount,gp.user_rank FROM " . 
	      $os->table('group_promotion_goods') . " gpg LEFT JOIN (" . $os->table('group_promotion_goods_type') . 
	      " t CROSS JOIN " . $os->table('group_promotion') . " gp) ON (gpg.goods_type_id=t.goods_type_id AND ".
	      " gpg.group_promotion_id=gp.group_promotion_id) WHERE gpg.goods_type_id = " . intval($filters->type) . " AND gpg.goods_id = " . 
	      intval($filters->goods_id) . " LIMIT 1";    
    $tmp_c_row = $db->getRow($sql);
    if($_SESSION['user_id']>0){
		$user_info   = get_user_info($_SESSION['user_id']);    
	    //检测用户等级是否有权限购买该商品
	    if(!check_user_rank_validate($tmp_c_row['user_rank'],$user_info)){
	    	 $res['error'] = '对不起，您目前的等级不能购买套装！';
	    }
    	// 启用新的库存管理操作
    	$sql_inventory = "select i.goods_number_available from " . $GLOBALS['os']->table('goods_inventory') . " as i where i.goods_id = ".$filters->goods_id." and i.color_id = ".$filters->color_id." and i.size_id = ".$filters->size_id;
    	$row = $GLOBALS['db']->getRow($sql_inventory);
    	$inventory_number = '';        
    	if ($row) {
    		$inventory_number = $row['goods_number_available'];
    	}else{
       		$inventory_number = 0;
    	}    
    	$number = 1;
    	if ($number > $inventory_number) {
    		$res['error'] = '对不起，该商品已经库存不足暂停销售。';
    	} 	    
    }
    $goods = get_goods_info($tmp_c_row['goods_id']);   
    if($tmp_c_row['price_type']==1){
    	$tmp_c_row['goods_price'] = price_format($tmp_c_row['add_money'] / $tmp_c_row['goods_count'],false);
    }elseif($tmp_c_row['price_type']==2){
    	if($tmp_c_row['is_present']==1){
    		$tmp_c_row['goods_price'] = price_format($tmp_c_row['add_money'] / $tmp_c_row['goods_count'],false);
    	}else{
    		$tmp_c_row['goods_price'] = price_format($goods['shop_price'] * ($tmp_c_row['discount']/100),false);
    	}
    }
    $tmp_c_row = array_merge($tmp_c_row,array_slice($goods,3,1));   
    $gc_row = array();
    $sql = "SELECT goods_color_id,color_id,color_name,adjust_price,img_id FROM ".$GLOBALS['os']->table('goods_color').
           " WHERE goods_id=".intval($filters->goods_id)." AND color_id=".intval($filters->color_id);
    $gc_row = $db->getRow($sql);

	$gg_row = $db->getRow("SELECT img_id,goods_id,thumb_url,img_desc FROM ".$os->table('goods_gallery')." WHERE goods_id=".
	                       intval($filters->goods_id)." AND color_id=".intval($filters->color_id).
	                       " AND type=1 ORDER BY sort_order,img_id DESC LIMIT 1");   
	if(empty($gg_row)){
   	   $gg_row = array();		
	}                  
    $gs_row = array();
    $sql = "SELECT goods_size_id,size_id,size_name,adjust_price FROM ".$GLOBALS['os']->table('goods_size')." WHERE goods_id=".
           intval($filters->goods_id)." AND size_id=".intval($filters->size_id);
    $gs_row = $db->getRow($sql);
    $tmp_c_row = array_merge($tmp_c_row,$gc_row,$gs_row,$gg_row);
    unset($goods,$user_info,$gc_row,$gs_row,$gg_row); 
    if($tmp_c_row === false){
		$res['message'] = 'error';
    }else{    
        $res['data'] = $tmp_c_row;
        /* 修正商品图片 */
        $tmp_c_row['goods_thumb']   = get_image_path($tmp_c_row['goods_id'], $tmp_c_row['thumb_url'], true);
    	$smarty->assign('gpg_item',$tmp_c_row);
    }
    $res['html']  = $smarty->fetch('library/tmp_cart.lbi');
	die($json->encode($res));	
}elseif($_REQUEST['act']=='buy'){
    /* 判断是否登录 */
    if ($_SESSION['user_id'] <= 0){
        show_message('对不起，您没有登录，不能参加团购，请您先登录！', '', '', 'error');
    }
    $group_promotion_id = isset($_POST['group_promotion_id']) ? intval($_POST['group_promotion_id']) : 0;
    if ($group_promotion_id <= 0)
    {
        os_header("Location: ./\n");
        exit;
    } 
    /* 取得商品套装信息 */
    $group_pro = group_pro_info($group_promotion_id);
    
    if (empty($group_pro)){
        os_header("Location: ./\n");
        exit;
    }

    /* 活动是否已结束 */
    if ($group_pro['status_no'] != UNDER_WAY)
    {
        show_message('该套装商品尚未进行中，不能购买', '', '', 'error');
    } 
    		    
    /* 清空购物车中所有套装商品 */
    include_once(ROOT_PATH . 'includes/lib_order.php');
    clear_cart(CART_GROUP_PROMOTION_GOODS);
    
    for($i=0;$i<count($_POST['goods_ids']);$i++){
    	$exsits_rec = $db->getOne("SELECT count(*) FROM ".$os->table('cart')." WHERE goods_id=".intval($_POST['goods_ids'][$i]).
    	                          " AND color_id=".intval($_POST['color_ids'][$i])." AND size_id=".intval($_POST['size_ids'][$i]).
    	                          " AND rec_type=".CART_GROUP_PROMOTION_GOODS);
    	if($exsits_rec && $exsits_rec>0){
    		$db->query("UPDATE ".$os->table('cart')." SET goods_price=".get_group_pro_goods_price($group_pro,intval($_POST['group_pro_goods_type'][$i]),intval($_POST['goods_ids'][$i])).
    		           ",goods_number=goods_number+1 WHERE goods_id=".intval($_POST['goods_ids'][$i])." AND color_id=".
    		           intval($_POST['color_ids'][$i])." AND size_id=".intval($_POST['size_ids'][$i])." AND rec_type=".CART_GROUP_PROMOTION_GOODS);	
    	}else{  
    		// 添加商品数量以适应商品套装的库存相关操作
    		$number = 1;
    		// End ADD
	    	$goods = goods_info(intval($_POST['goods_ids'][$i]));
		    $cart = array(
		        'user_id'        => $_SESSION['user_id'],
		        'session_id'     => SESS_ID,
		        'goods_id'       => $goods['goods_id'],
		        'goods_sn'       => addslashes($goods['goods_sn']),
		        'goods_name'     => addslashes($goods['goods_name']),
		        'market_price'   => $goods['market_price'],
		    	'goods_price'    => get_group_pro_goods_price($group_pro,intval($_POST['group_pro_goods_type'][$i]),intval($_POST['goods_ids'][$i])),		    
		        'goods_number'   => $number,
		        'goods_attr'     => get_goods_spec_info($spec_ids = array('color_id'=>intval($_POST['color_ids'][$i]),'size_id'=>intval($_POST['size_ids'][$i]))),
		        'goods_attr_id'  => implode(',',$spec_ids),
		        'is_real'        => $goods['is_real'],
		        'extension_code' => addslashes($goods['extension_code']),
		        'parent_id'      => 0,
		        'rec_type'       => CART_GROUP_PROMOTION_GOODS,
		    	'color_id'      => intval($_POST['color_ids'][$i]),
		    	'size_id'       => intval($_POST['size_ids'][$i]),
		        'is_gift'        => 0
		    );
		    
    		$db->autoExecute($os->table('cart'), $cart, 'INSERT'); 			
    	}
    }
    /* 记录购物流程类型：团购 */
    $_SESSION['flow_type'] = CART_GROUP_PROMOTION_GOODS;
    $_SESSION['extension_code'] = 'group_promotion';
    $_SESSION['extension_id'] = $group_promotion_id;

    /* 进入收货人页面 */
    os_header("Location: ./flow.php?step=consignee\n");
    exit;
}elseif ($_GET['act']=='switch_color_img'){
    
    include('includes/cls_json.php');
    $json = new JSON;
    $filters = $json->decode($_GET['JSON']);
    
    $res    = array('err_msg' => '', 'result' => '');

    $color_id = isset($filters->color_id) ? intval($filters->color_id) : 0;
    if ($color_id == 0){
        $res['err_msg'] = '颜色参数值丢失。';
        $res['err_no']  = 1;
    }else{
        $_gc_row=$db->getRow("SELECT gc.color_id,g.goods_id,g.goods_name FROM ".$os->table('goods_color')." gc LEFT JOIN ".
                             $os->table('goods')." g ON gc.goods_id=g.goods_id WHERE gc.goods_id=".intval($filters->goods_id).
                             " AND gc.color_id='$color_id' LIMIT 1");            
        if($_gc_row && $_gc_row['goods_id']>0){
            $color_gg=$db->getAll("SELECT * FROM ".$os->table('goods_gallery')."  WHERE goods_id='$_gc_row[goods_id]' ".
                                  " AND color_id='$_gc_row[color_id]' AND type=1 ORDER BY sort_order,img_id DESC"); 
            $res['result'] = array('list'=>$color_gg,'goods_name'=>$_gc_row['goods_name']);
        }else{
            $res['err_msg'] = '参数值不存在。';
            $res['err_no']  = 1;                    
        }
    }
    die($json->encode($res));   
}

/**
 * 取得商品套装活动数量
 * @return  int
 */
function group_pro_count()
{
    $now = gmtime();
    $sql = "SELECT COUNT(*) " .
            "FROM " . $GLOBALS['os']->table('group_promotion') .
            "WHERE start_time <= '$now'";

    return $GLOBALS['db']->getOne($sql);
}

/**
 * 取得某页的商品套装活动
 * @param   int     $size   每页记录数
 * @param   int     $page   当前页
 * @return  array
 */
function group_pro_list($size, $page)
{
    $gp_list = array();
    $group_pro['finished'] = $group_pro['finished'] = array();
    $now = gmtime();
    $sql = "SELECT *, start_time AS start_date, end_time AS end_date FROM ".$GLOBALS['os']->table('group_promotion').
           " WHERE start_time <= '$now' ORDER BY group_promotion_id DESC";
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);
    $gp_list['under_way'] = array();
    $gp_list['finished'] = array();    
    while ($group_pro = $GLOBALS['db']->fetchRow($res)){
    	$sql = "SELECT IFNULL(thumb_url, '') AS thumb_url FROM ".$GLOBALS['os']->table('group_promotion_gallery').
    	       " WHERE is_reveal = 1 AND group_promotion_id='$group_pro[group_promotion_id]' ORDER BY img_id DESC LIMIT 1";
    	$group_pro['thumb_url'] = $GLOBALS['db']->getOne($sql);
    	
        $group_pro['status_no'] = auction_status($group_pro);
        
        $group_pro['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $group_pro['start_time']);
        $group_pro['end_time']   = local_date($GLOBALS['_CFG']['time_format'], $group_pro['end_time']);    
         
        $group_pro['group_pro_chat'] = $group_pro['price_type']==1 ? ('组合价'.price_format($group_pro['price'])) : ('折扣'.$group_pro['discount'].'%');     
	   	/* 取得用户等级 */
	    $user_rank_list = array();
	    $sql_rank = "SELECT rank_id, rank_name FROM " . $GLOBALS['os']->table('user_rank');
	    $res_rank = $GLOBALS['db']->query($sql_rank);
	    while ($row_rank = $GLOBALS['db']->fetchRow($res_rank))
	    {
	        if(strpos(',' . $group_pro['user_rank'] . ',', ',' . $row_rank['rank_id']. ',') !== false){
	            $user_rank_list[] = $row_rank['rank_name'];
	        }
	    }
	    $group_pro['user_rank_list'] = implode(',',$user_rank_list);
        $group_pro['group_pro_thumb'] = get_image_path($group_pro['group_promotion_id'], $group_pro['thumb_url'], true);
        $group_pro['url'] = build_uri('group_promotion', array('gpid'=>$group_pro['group_promotion_id']));
        if($group_pro['status_no'] < 2){
            $gp_list['under_way'][] = $group_pro;
        }else{
            $gp_list['finished'][] = $group_pro;
        }      
    }   
    $gp_list = array_merge($gp_list['under_way'], $gp_list['finished']);
    return $gp_list;
}
?>